package com.quick.proxy.client;

import com.quick.proxy.core.ChannelAttribute;
import com.quick.proxy.core.ChannelConstants;
import com.quick.proxy.core.utils.ResponseUtils;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * Description: 代理资源
 * Author: 吃素不吃肉
 * Date: 2023/7/5
 *
 * @author 吃素不吃肉
 */
@Slf4j
public class ProxyResources {
    /**
     * 清理真实通道
     *
     * @param channel 通道
     */
    public static void clearRealProxyResources(Channel channel) {
        //获取访问者id
        String visitorId = channel.attr(ChannelAttribute.VISITOR_ID).get();
        if (visitorId == null) {
            return;
        }
        //移除访问者id的真实代理通道
        Channel proxyChannel = ChannelConstants.VISITOR_ID_PROXY_CHANNEL.get(visitorId);
        if (proxyChannel != null) {
            Map<String, Channel> visitorIdRealProxyChannel = proxyChannel.attr(ChannelAttribute.VISITOR_ID_REAL_PROXY_CHANNEL).get();
            if (!CollectionUtils.isEmpty(visitorIdRealProxyChannel)) {
                visitorIdRealProxyChannel.remove(visitorId);
            }
            //通知代理服务端,真实客户端连接断开
            ResponseUtils.disabledConnect(visitorId, proxyChannel);
            //移除访问者id的代理通道
            ChannelConstants.VISITOR_ID_PROXY_CHANNEL.remove(visitorId);
        }
        log.info("visitorId[{}]真实代理客户端连接断开", visitorId);
    }


}
